package pgcoin

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/algorithm/uniquecode"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
)

// GetTransactionList 获取盘古币流水列表
func (c *sPgCoin) GetTransactionList(ctx context.Context, in model.PGCoinTransactionListInput) (out *model.PGCoinTransactionListOutput, err error) {
	out = &model.PGCoinTransactionListOutput{}
	// 获取查询条件
	err = c.TransactionWhereModel(ctx, in.PGCoinTransactionWhere).
		Page(in.Page, in.Size).
		OrderDesc(dao.PanguCoinTransaction.Columns().Id).
		ScanAndCount(&out.Rows, &out.Total, false)
	return
}

// GenPGCoinTransaction 生成盘古币流水记录
func (c *sPgCoin) GenPGCoinTransaction(ctx context.Context, uid, coin uint, tranType enums.PGCoinTransactionType) (tno string, err error) {
	// 获取用户资金
	funds, err := service.User().GetFundsDetailByUid(ctx, uid)
	if err != nil {
		return ``, err
	}
	var (
		pgCoin      = int(coin)
		afterPGCoin = funds.AvailablePanguCoin
	)

	// 交易类型
	switch tranType {
	case enums.PGCoinTransactionTypeConsume:
		// 支出
		pgCoin = pgCoin * -1 // 转为负数
		afterPGCoin -= coin
	default:
		// 收入
		afterPGCoin += coin
	}

	// 流水单号
	tno = uniquecode.UniSerialCode(ctx, consts.PanGuCoinTransactionPrefix, true)

	// 创建收入流水
	_, err = dao.PanguCoinTransaction.Ctx(ctx).
		OmitEmpty().
		Insert(entity.PanguCoinTransaction{
			Uid:             uid,
			TransactionNo:   tno,
			BeforePanguCoin: funds.AvailablePanguCoin,
			PanguCoin:       pgCoin,
			AfterPanguCoin:  int(afterPGCoin),
			Remark:          tranType.Fmt(),
			Type:            uint(tranType),
		})
	if err != nil {
		return ``, exception.New(`生成盘古币流水失败`)
	}
	return
}
